<?php

/**
 * 合同应收款信息仓库
 * @author wangwx 2015-5-12
 */

namespace common\repositories\myhtsq;

use common\entities\ConfigEntity;
use Exception;
use common\support\StringHelper;
use common\error\ErrorCode;
use common\repositories\BaseRepository;
use common\entities\myhtsq\ContractReceivableEntity;
use common\entities\myhtsq\InvoiceEntity;
use common\repositories\myhtsq\ErpUserRepository;

class ContractReceivableRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 根据合同ID获取对应的应收款项明细
     * @param string $contractId 合同id
     * @param boolean $withBadDebt 是否包含坏账
     * @return array
     */
    public static function getReceivableInfoByContractId($contractId, $withBadDebt = true)
    {
        $query = ContractReceivableEntity::find()
            ->select("myscrm_contract_receivable.*,receivableItem.receivable_item_name,categoryItem.money_category_item_name,
                    myscrm_buss_account_types.type_name as revenue_type_name,myscrm_erp_user.UserName as payee_name,user.UserName as joint_saler_name,myscrm_erp_business_unit.BUName as department_name,
                    myscrm_invoice_receivable.cur_billing_amount")
            ->leftJoin('myscrm_receivable_item receivableItem', 'myscrm_contract_receivable.receivable_item_id = receivableItem.receivable_item_id')
            ->leftJoin('myscrm_money_category_item categoryItem', 'myscrm_contract_receivable.money_category_item_id = categoryItem.money_category_item_id')
            ->leftJoin('myscrm_buss_account_types', 'myscrm_contract_receivable.revenue_type = myscrm_buss_account_types.type_id')
            ->leftJoin('myscrm_erp_user', 'myscrm_contract_receivable.payee_id = myscrm_erp_user.UserGUID')
            ->leftJoin('myscrm_erp_user user', 'myscrm_contract_receivable.joint_saler = user.UserGUID')
            ->leftJoin('myscrm_erp_business_unit', 'myscrm_contract_receivable.department_id = myscrm_erp_business_unit.BUGUID')
            ->leftJoin('myscrm_invoice_receivable', 'myscrm_contract_receivable.receivable_id = myscrm_invoice_receivable.receivable_id')
            ->where(['myscrm_contract_receivable.contract_id' => $contractId]);

        if (!$withBadDebt) {
            $query->andWhere('is_bad_debt != 1');
        }

        $query = $query->asArray()
            ->all();

        if (isset($query) && count($query) > 0) {
            foreach ($query as $k => $v) {
                $invoices = self::getInvoiceInfoByReceivableId($v['receivable_id']);
                $invoiceNos = '';
                if (isset($invoices) && count($invoices) > 0) {
                    foreach ($invoices as $k1 => $v1) {
                        $invoiceNos += $v1['invoice_no'] + ';';
                    }

                    $invoiceNos = substr($invoiceNos, 0, strlen($invoiceNos) - 1);
                }
                $query[$k]['billing_invoice_no'] = $invoiceNos;
            }
        }

        return $query;
    }

    /**
     * 获取指定合同下的所有应收款金额
     * @param string $contractId 合同id
     * @return float
     */
    public static function getReceivableTotalAmountByContractId($contractId)
    {
        $totalAmount = 0;
        $query = ContractReceivableEntity::find()
            ->select('receivable_amount')
            ->where(['contract_id' => $contractId])
            ->andWhere('is_bad_debt = 0')
            ->asArray()
            ->all();

        if (isset($query) && count($query) > 0) {
            foreach ($query as $k => $v) {
                if (isset($v['receivable_amount']) && !empty($v['receivable_amount'])) {
                    $totalAmount += floatval($v['receivable_amount']);
                }
            }
        }

        return $totalAmount;
    }

    /**
     * 获取应收款ID获取已开票的发票信息
     * @param string $receivableId
     * @return array
     */
    public static function getInvoiceInfoByReceivableId($receivableId)
    {
        $query = InvoiceEntity::find()
            ->select('myscrm_invoice.*')
            ->leftJoin('myscrm_invoice_receivable', 'myscrm_invoice_receivable.invoice_id = myscrm_invoice.invoice_id')
            ->where(['receivable_id' => $receivableId])
            ->asArray()
            ->all();
        return $query;
    }

    /**
     * 根据应收款项Id获取对应的应收款
     * @param string $receivableId 应收款项Id
     * @return \common\entities\myhtsq\ContractReceivableEntity
     */
    public static function getContractReceivableById($receivableId)
    {
        return ContractReceivableEntity::findOne(['receivable_id' => $receivableId]);
    }

    /**
     * 新增合同应收款项
     * @param common\models\myhtsq\ContractReceivableModel $contractReceivableModel
     * @return boolean|string 失败返回false，成功返回应收款项Id
     */
    public static function addContractReceivable($contractReceivableModel)
    {
        try {
            $entity = new ContractReceivableEntity();
            $entity->setAttributes($contractReceivableModel->attributes);
            $entity->created_on = ConfigEntity::getDbNowDate();
            if (!(isset($entity->receivable_id) && !empty($entity->receivable_id))) {
                $entity->receivable_id = StringHelper::uuid();
            }

            $result = $entity->save();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 修改合同应收款项
     * @param common\models\myhtsq\ContractReceivableModel $contractReceivableModel
     * @return boolean|string 失败返回false，成功返回应收款项Id
     */
    public static function updateContractReceivable($contractReceivableModel)
    {
        try {
            $entity = ContractReceivableEntity::find()->where(['receivable_id' => $contractReceivableModel->receivable_id])->one();
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_NOT_EXISTS);
            }

            $entity->setAttributes($contractReceivableModel->attributes);
            $entity->modified_on = ConfigEntity::getDbNowDate();
            $result = $entity->update();
            if ($result < 0) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->receivable_id;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 获取应收到期日未收应收款
     * @param $expiredDate 到期日
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getReceivableExpiredRemind($expiredDate)
    {
        $query = ContractReceivableEntity::find()
            ->where(['receivable_date' => $expiredDate, 'is_bad_debt' => '0'])
            ->andWhere('receivable_amount<>received_amount')
            ->asArray()
            ->all();
        return $query;
    }

    /**
     * 获取发票对应的未回完款的应收
     * @param $invoiceId 发票id
     */
    public static function getNoReceivedByInvoice($invoiceId)
    {
        $query = ContractReceivableEntity::find()
            ->select('myscrm_contract_receivable.*')
            ->innerJoin('myscrm_invoice_receivable', 'myscrm_invoice_receivable.receivable_id=myscrm_contract_receivable.receivable_id and myscrm_contract_receivable.billing_amount<>myscrm_contract_receivable.received_amount')
            ->where(['myscrm_invoice_receivable.invoice_id' => $invoiceId])
            ->asArray()
            ->all();
        return $query;
    }

    public static function getContractReceivedByContractId($contractid)
    {
        $query = ContractReceivableEntity::find()->where(['contract_id'=>$contractid])->all();
        if(empty($query)){
            return 0;
        }else{
            $totalAmount = 0;
            foreach ($query as $q) {
                $totalAmount += floatval($q['received_amount']);
            }
            return $totalAmount;
        }
    }

    public static function isGeneralReceived($revenue_type,$receivable_item_id,$money_category_item_id,$receivable_date,$contractid){
        $entity = ContractReceivableEntity::find()->where(['revenue_type' => $revenue_type,'receivable_item_id'=>$receivable_item_id,'money_category_item_id'=>$money_category_item_id,'receivable_date'=>$receivable_date,'contract_id'=>$contractid])->one();
        return $entity;
    }
}
